<template>
  <a-popover
    trigger="click"
    :visible="gatewayTypeId ? attrVisible : false"
    placement="left"
    @visible-change="visibleChange"
  >
    <template #content>
      <div style="max-width: 250px">
        <a-table
          size="small"
          :columns="columns"
          :data-source="tableData"
          :loading="tableLoading"
          :pagination="false"
          :scroll="{ y: 280 }"
        >
          <template #bodyCell="{ record, column }">
            <Icon
              v-if="column.dataIndex === 'requires'"
              :type="record.requires ? 'icon-duihao' : 'icon-guanbi'"
              :class="[record.requires ? 'text-color-success' : 'text-color-danger']"
            />
          </template>
        </a-table>
      </div>
    </template>
    <a-button type="link" :disabled="!gatewayTypeId" :style="btnStyle">查看点位属性</a-button>
  </a-popover>
</template>
<script setup lang="ts">
import { SelectProps, TableColumnProps } from "ant-design-vue";
import { CSSProperties, ref } from "vue";
import { GatewayTypeAttrItem } from "/@/api/aiot/gateway/models";
import { useCURD } from "/@/hooks/useCURD";
import { Api } from "/@/api/aiot/gateway";

const props = defineProps<{
  gatewayTypeId?: string;
  btnStyle?: CSSProperties;
}>();

const attrVisible = ref(false);
let lastValue: string | null = null;
function visibleChange(v) {
  if (!props.gatewayTypeId) return;
  attrVisible.value = v;
  if (lastValue === null || props.gatewayTypeId !== lastValue) {
    lastValue = props.gatewayTypeId as string;
    reloadTable({ model: { gatewayTypeId: lastValue } });
  }
}

const columns = ref<TableColumnProps<GatewayTypeAttrItem>[]>([
  { title: "属性名称", dataIndex: "datapointAttrName" },
  { title: "是否必填", dataIndex: "requires", align: "center" },
]);
const { tableData, tableLoading, reloadTable } = useCURD<GatewayTypeAttrItem>({
  getPageUrl: Api.getGatewayTypeAttrs,
  loadOnMounted: false,
  pageSize: 999,
  loadFilter(data) {
    data.sort((a, b) => {
      return a.datapointAttrNumber - b.datapointAttrNumber;
    });
    return data;
  },
});
</script>
